<template>
    <div class="box">
        <h1 style="text-align: center;">用户列表</h1>
        <br>
        <el-button type="primary" @click="router.push('/user/add')"
            v-permission="{ path: '/user/add', name: '用户添加' }">添加用户</el-button>
        <el-table :data="UserList.data" height="500" border style="width: 100%">
            <el-table-column prop="username" label="用户名">
            </el-table-column>
            <el-table-column prop="email" label="邮箱">
            </el-table-column>
            <el-table-column prop="tel" label="手机号">
            </el-table-column>
            <el-table-column label="角色" width="100">
                <template #default="scope">
                    <span>{{ scope.row.role ? scope.row.role.name : '前台用户' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="启用" width="70">
                <template #default="scope">
                    <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949"
                        @change="onChange(scope.row._id)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="注册时间">
                <template #default="scope">
                    {{ time(scope.row.createdAt) }}
                </template>
            </el-table-column>
            <el-table-column label="修改时间">
                <template #default="scope">
                    {{ time(scope.row.updatedAt) }}
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" v-permission="{ path: '/user/edit', name: '用户修改' }"
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" v-permission="{ path: '/user/fel', name: '用户删除' }"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 编辑用户的弹窗 -->
        <el-dialog title="用户编辑" v-model="dialogVisible" width="30%">
            <el-form :model="form" ref="formref" label-width="80px">
                <el-form-item label="用户名">
                    <el-input v-model="form.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密  码">
                    <el-input v-model="form.password" type="password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮  箱">
                    <el-input v-model="form.email" type="email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="form.tel" type="tel" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-switch v-model="form.enable" active-color="#13ce66" inactive-color="#ff4949">
                    </el-switch>
                </el-form-item>
                <el-form-item label="用户权限">
                    <el-select v-model="form.role" placeholder="请选择角色">
                        <el-option v-for="role in roles.data" :key="role._id" :label="role.name"
                            :value="role._id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="close">取 消</el-button>
                <el-button type="primary" @click="onSubmit(onEdit)">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script setup>
import { userList, changeEnable, userEdit, roleList, userDel } from '@/request'
import moment from 'moment'
import permission from '@/utils/permission'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

const vPermission = permission


let UserList = reactive({
    data: [
        // {
        //     role: {
        //         name: ''
        //     }
        // }
    ]
})
let dialogVisible = ref(false)
let form = reactive({
    username: '',
    password: '',
    email: '',
    tel: '',
    enable: false,
    role: ''
})
let roles = reactive({ data: [] })


let handleEdit = (index, row) => {
    console.log(row);
    dialogVisible.value = true
    row.password = ''
    if (row.role !== null) {
        row.role = row.role.name
    } else {
        row.role = '前台用户'
    }
    for (let key in row) {
        form[key] = row[key]
    }
    getUserList()
}
let handleDelete = (index, row) => {
    ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        userDel(row._id).then(res => {
            if (res.error_code === 200) {
                UserList.splice(index, 1)
                ElMessage({
                    type: 'success',
                    duration: 1500,
                    message: res.msg,
                    onClose: () => {
                        getUserList()
                    }
                })
            } else {
                ElMessage({
                    type: 'error',
                    duration: 1500,
                    message: res.msg
                })
            }
        })
    })
}
let getUserList = async () => {
    let data = await userList()
    console.log(data);
    if (data.error_code === 200) {
        UserList.data = data.data
    }
    // console.log(this.userList);
    let index = UserList.data.findIndex(item => {
        if (item.role) {
            // console.log(item.role.name);
            return item.role.name === '超级'
        }
    })
    UserList.data.splice(index, 1)
}
let getRoles = async () => {
    let data = await roleList()
    roles.data = data.data.rolelist
    // console.log(roles);
}
let onChange = async (id) => {
    let data = await changeEnable(id)
    let { error_code, msg } = data
    if (error_code === 200) {
        ElMessage({
            type: 'success',
            duration: 1500,
            message: msg
        })
    } else {
        ElMessage({
            type: 'error',
            duration: 1500,
            message: msg
        })
    }
}
let onEdit = async () => {
    // console.log(this.form);
    let data = await userEdit(form)
    if (data.error_code === 200) {
        ElMessage({
            message: data.msg,
            type: 'success',
            duration: 1500,
            onClose: () => {
                dialogVisible.value = false
                getUserList()
            }
        });
    } else {
        ElMessage({
            message: data.msg,
            type: 'error'
        })
    }
}
let close = () => {
    getUserList()
    dialogVisible.value = false
}
let onSubmit = (done) => {
    ElMessageBox.confirm('确认修改？')
        .then(res => {
            done()
        })
}


getUserList()
getRoles()


let time = computed(() => {
    return (value) => {
        return moment(value).format('YYYY-MM-DD HH:mm:ss')
    }
})


</script>

<style>
.el-table,
.box {
    height: 90% !important
}
</style>
